import React, { useState, useEffect } from 'react';
import './App.css';
import FileSearch from './components/FileSearch';
import FileList from './components/FileList';
import BottomBtn from './components/BottomBtn'
import TabList from './components/TabList'
import { defaultFiles } from './utils/index';
import 'bootstrap/dist/css/bootstrap.min.css';
import { faPlus, faFileImport, faSave } from '@fortawesome/free-solid-svg-icons'
import SimpleMdEditor from 'react-simplemde-editor'
import "easymde/dist/easymde.min.css";
import uuidv4 from 'uuid/dist/v4'
import fsHelper from './utils/fileHelper'
import { mapToArray, clicpFilePath } from './utils/helper'
import useIpcRenderer from './hooks/useIpcRenderer'

const { dialog, app } = window.require('electron').remote;
const path = window.require('path');
const { ipcRenderer } = window.require('electron')

const Store = window.require('electron-store');

const filestore = new Store({ "name": "files Data" })
const fileLocationStore = new Store({ name: "savedFileLocation" })

const objStoreFiles = (files) => {
  const storeData = files.reduce((result, file) => {
    const { title, path, id } = file;
    result[id] = {
      path,
      title,
      id,
    }

    return result
  }, {})
  filestore.set('files', storeData);
}

function App() {
  const [files, setfiles] = useState(filestore.get('files') ? mapToArray(filestore.get('files')) : [])
  const [tabFiles, settabFiles] = useState([])

  const [activeFileId, setactiveFileId] = useState('')
  const [unsavedIds, setunsavedIds] = useState([])
  const [serarchFiles, setSearchFiles] = useState([]);

  const savedLocation = fileLocationStore.get('savedFileLocation') ? fileLocationStore.get('savedFileLocation') : app.getPath('desktop');

  useIpcRenderer({
    'create-new-file': () => { createNewFile() },
    'import-file': () => { importFiles() },
    'save-edit-file': () => { onSaveActivedFile() },
  })


  //编辑了文件名
  const fileEdited = async (id, value) => {
    const savePath = path.join(savedLocation, `${value}.md`)
    const existFile = files.find(file => file.path === savePath && file.id !== id)
    console.log('existFile', existFile);
    if (existFile) {
      dialog.showMessageBox({
        message: '提示',
        detail: '该文件位置处已经存在了该文件',
        type: 'error',
      })
      const filterFiles = files.filter(file => file.id !== id);
      setfiles(filterFiles);
      return
    }

    const filesCopy = await Promise.all(files.map(async function (item) {
      if (item.id === id) {
        if (item.isNew === true) {
          const reuslt = await fsHelper.writeFile(savePath, item.body)
          item.isNew = false
        } else {
          //编辑
          const originPath = path.join(savedLocation, `${item.title}.md`)
          const result = await fsHelper.reanmeFile(originPath, savePath)
          console.log('result', result);
        }
        item.title = value
        item.path = savePath
      }
      return item
    }))
    console.log('filesCopy', filesCopy);
    setfiles(filesCopy);
    objStoreFiles(filesCopy)
  }

  useEffect(() => {
    console.log('unsavedIds', unsavedIds);
  }, [unsavedIds])

  const onCloseTab = (id, operateId) => {
    setunsavedIds([...unsavedIds.filter(item => item !== id)]);
    const nowTabFiles = tabFiles.filter(item => item.id !== id)
    const length = nowTabFiles.length;
    settabFiles(nowTabFiles);
    if (operateId === 0) {
      const willsavedFile = files.find(item => item.id === id);
      fsHelper.writeFile(willsavedFile.path, willsavedFile.body);
    }
    if (length) {
      setactiveFileId(nowTabFiles[length - 1].id);
    } else {
      setactiveFileId('');
    }

  }

  const onLeftFileclick = async (id) => {
    setactiveFileId(id);
    if (tabFiles.find(item => item.id === id)) {
      return;
    }
    const tabFilesCopy = [...tabFiles];
    const file = files.find(item => item.id === id)
    console.log(file);
    const data = await fsHelper.readFile(file.path);
    console.log('data', data);
    file.body = data;
    tabFilesCopy.push(file)
    settabFiles(tabFilesCopy)

  }
  //文件搜索
  const fileSearch = (value) => {
    const newFiles = files.filter(item => item.title.includes(value));
    setSearchFiles(newFiles);
  }

  //编辑文件
  const fileChange = (id, value) => {
    const newfiles = files.map(item => {
      if (item.id === id) {
        if (!unsavedIds.includes(id) && item.body !== value) {
          setunsavedIds([...unsavedIds, id])
        }
        item.body = value

      }
      return item
    })
    setfiles(newfiles);
  }

  //删除文件
  const deleteFile = (id) => {
    const newFiles = files.filter(item => item.id !== id);
    const newTabFiles = tabFiles.filter(item => item.id !== id);
    const length = newTabFiles.length;
    const deleteFile = files.find(file => file.id === id);
    if (deleteFile.path) {
      fsHelper.deleteFile(deleteFile.path).then(() => {
        console.log('删除成功')
        dialog.showMessageBox({
          message: `提示`,
          detail: '删除成功',
          type: 'info',
        })
      }

      ).catch(err => {
        console.log('err', err);
      });
    }

    if (length) {
      setactiveFileId(newTabFiles[length - 1].id)
    } else {
      setactiveFileId('');
    }
    settabFiles(newTabFiles)
    setfiles(newFiles);
    objStoreFiles(newFiles);
  }

  //新建文件
  const createNewFile = () => {
    const newFile = {
      id: uuidv4(),
      title: '',
      body: '## 请输入markDown',
      isNew: true,
    }
    setfiles([...files, newFile])
  }

  //保存文件
  const onSaveActivedFile = () => {
    const file = files.find(item => item.id == activeFileId);
    const savePath = path.join(savedLocation, `${file.title}.md`)
    fsHelper.writeFile(savePath, file.body).then(() => {
      setunsavedIds(unsavedIds.filter(id => id !== file.id))
    }).catch(err => {
      console.log('err', err);
    })
  }

  //导入文件
  const importFiles = () => {
    dialog.showOpenDialog({
      title: '请选择 Markdown 文件',
      properties: ['openFile', 'multiSelections'],
      filters: [{
        name: 'markdown', extensions: ['md']
      }]
    }).then(result => {
      if (!result.canceled) {
        const filePaths = result.filePaths;
        console.log('filepaths', filePaths);
        const importFiles = filePaths.map(path => {
          return {
            id: uuidv4(),
            title: clicpFilePath(path),
            path,
          }
        }).filter(file => { console.log(JSON.parse(JSON.stringify(files))); return files.find(item => item.path === file.path) ? false : true })

        setfiles([...files, ...importFiles])
        objStoreFiles([...files, ...importFiles])
      }
    }).catch(err => {
      console.log('err', err);
    });
  }


  const filesArr = serarchFiles.length > 0 ? serarchFiles : files;
  return (
    <div className="App container-fluid px-0">
      <div className='row no-gutters'>
        <div className='col-4 left-panel'>
          <FileSearch title='我的云文档' onFileSearch={fileSearch}></FileSearch>
          <FileList
            files={filesArr}
            onFileClick={onLeftFileclick}
            onFileDelete={deleteFile}
            onFileEdit={fileEdited}
          />
          <div className='row no-gutters bottom-btns'>
            <div className="col">
              <BottomBtn icon={faPlus} text='新建' colorClass='btn-primary' onClick={createNewFile}></BottomBtn>
            </div>
            <div className="col">
              <BottomBtn icon={faFileImport} text='导入' colorClass='btn-success' onClick={importFiles}></BottomBtn>
            </div>
            <div />
          </div>
        </div>
        <div className='col-8 right-panel'>
          {
            !activeFileId && <div className='start-page'>
              选择或者创建新的MarkDown文档
            </div>
          }
          {
            activeFileId && <div>
              <TabList files={tabFiles} unsavedIds={unsavedIds} onTabClick={(id) => { console.log(id); setactiveFileId(id) }} activeId={activeFileId} oncloseTab={onCloseTab}></TabList>
              <SimpleMdEditor key={activeFileId !== '' && activeFileId} value={files.find(item => item.id === activeFileId)?.body} options={{ minHeight: '500px' }} onChange={(value) => { fileChange(activeFileId, value) }}></SimpleMdEditor>
              {/* <BottomBtn icon={faSave} text='保存' colorClass='btn-danger' onClick={onSaveActivedFile}></BottomBtn> */}
            </div>
          }

        </div>
      </div>
    </div>
  );
}

export default App;
